from django.core.management.base import BaseCommand, CommandError

from ceph.ceph_manager import global_configs, check_old_conf_name2


class Command(BaseCommand):
    '''
    检测/添加全局配置参数
    '''

    help = """ 
            检测/添加全局配置参数
            python manage.py check_global_config
            [manage.py check_global_config --radmin];
            [manage.py check_global_config --old-check-parameter];
            [manage.py check_global_config --nc-s3];
           """

    def add_arguments(self, parser):
        parser.add_argument(
            '--radmin', default=None, dest='radmin', nargs='?', const=True,
            help='中坤管理员格式校验',
        )

        parser.add_argument(
            '--old-check-parameter', default=None, dest='old-check-parameter', nargs='?', const=True,
            help='检查旧格式向新格式转换',
        )

        parser.add_argument(
            '--nc-s3', default=None, dest='nc-s3', nargs='?', const=True,
            help='检查和修正旧格式向新格式转换',
        )


    def handle(self, *args, **options):
        print(options)
        configs = None
        radmin = options['radmin']
        old_check_parameter = options['old-check-parameter']
        nc_s3_check = options['nc-s3']

        if old_check_parameter:
            try:
                check_old_conf_name2()
            except Exception as e:
                self.stdout.write(self.style.ERROR(
                    f"check error:{str(e)}"))

            return

        if radmin:
            try:
                global_configs.check_site_parameter_resource_admin()

            except Exception as e:
                self.stdout.write(self.style.ERROR(
                    f"check error:{str(e)}"))

            return

        if nc_s3_check:
            try:
                global_configs.check_site_parameter_nexcloud_s3()

            except Exception as e:
                self.stdout.write(self.style.ERROR(
                    f"check error:{str(e)}"))

            return

        try:
            configs = global_configs.get_configs_no_cache(remove_invalid=False)

        except Exception as e:
            self.stdout.write(self.style.ERROR(
                f"error check global config:{str(e)}"))

        self.stdout.write(
            self.style.SUCCESS(
                f'Successfully check global config:'
            )
        )
        for key, value in configs.items():
            print({key: value})

        return
